/**
 * Copyright (c) 2011 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

var lastUtterance = '';
var speaking = false;
var globalUtteranceIndex = 0;

function speak(utterance) {
  if (speaking && utterance == lastUtterance) {
    chrome.tts.stop();
    return;
  }

  speaking = true;
  lastUtterance = utterance;
  globalUtteranceIndex++;
  var utteranceIndex = globalUtteranceIndex;

  var rate = 1.0;
  var pitch = 1.0;
  var volume = 1.0;
  var voice = localStorage['voice'];
  chrome.tts.speak(
      utterance,
      {voiceName: voice,
       rate: parseFloat(rate),
       pitch: parseFloat(pitch),
       volume: parseFloat(volume),
       onEvent: function(evt) {
         if (evt.type == 'end' ||
             evt.type == 'interrupted' ||
             evt.type == 'cancelled' ||
             evt.type == 'error') {
           if (utteranceIndex == globalUtteranceIndex) {
             speaking = false;
           }
         }
       }
      });
}

function initBackground() {
  loadContentScriptInAllTabs();

  chrome.extension.onRequest.addListener(
      function(request, sender, sendResponse) {
        if (request['speak']) {
            speak(request['speak']);
        } else if (request['can_tts']) {
            if (localStorage['tts_mode'] == "on")
                sendResponse({'tts_activated': true});
            else
                sendResponse({'tts_activated' : false});
        } else if (request['can_helpRead']) {
            if (localStorage['helpread_mode'] == "on")
                sendResponse({'helpRead_activated': true});
            else
                sendResponse({'helpRead_activated' : false});
        } else if (request['tts_button']) {
            if (localStorage['tts_mode'] == 'on')
                localStorage['tts_mode'] = 'off';
            else
                localStorage['tts_mode'] = 'on';
        } else if (request['stop_tts']) {
            chrome.tts.isSpeaking(function(isSpeaking) {
                if (isSpeaking)
                    chrome.tts.stop();                    
            });
        }
      });
}

initBackground();
